/*
 * @Author: Lin Hongwei
 * @Date: 2022-09-18 20:37:33
 * @LastEditTime: 2022-10-08 20:17:38
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 项目列表的工具文件
 */
import { useMemo } from "react";
import { useParams } from "react-router";
import { useQueryProjectDetail } from "../../api/project";
import { useSetURLSearchParams, useUrlQueryParam } from "../../hooks/url";
import { cleanObject } from "../../utils";

/**
 * @description: 将personId转化为number后返回
 * @return {*} 返回处理过的hook
 */
export const useProjectSearchParams = () => {
  const [param, setParam] = useUrlQueryParam(["name", "personId"]);
  return [
    //由于返回的param被监听，所以需要经过useMemo处理，不然将造成死循环
    useMemo(
      () => ({
        ...param,
        personId: +param.personId || undefined,
      }),
      [param]
    ),
    setParam,
  ] as const;
};

/**
 * @description: 查询的项目列表查询的key值
 * @return {*}
 */
export const useProjectQueryKey = () => {
  const [param] = useProjectSearchParams();
  return ["projects", cleanObject(param || {})];
};

/**
 * @description: 模态框显示隐藏逻辑
 * @return {*}
 */
export const useProjectModal = () => {
  const [{ showProjectModal }, setVisible] = useUrlQueryParam([
    "showProjectModal",
  ]);

  const [{ id: projectId }, setProjectId] = useUrlQueryParam(["id"]); //项目id

  const setURLSearchParams = useSetURLSearchParams(); //统一修改url参数

  const open = () => setVisible({ showProjectModal: true });
  // const close = () => {
  //   setVisible({ showProjectModal: undefined }); //清除参数的话需要设置undefied（封装的时候已经进行排除）
  //   setProjectId({ id: undefined })
  // }
  const close = () =>
    setURLSearchParams({ showProjectModal: undefined, id: undefined });

  const { data: projectDetailData, isLoading } = useQueryProjectDetail(
    +projectId
  );

  const queryProjectDetailFromID = (id: number) =>
    setURLSearchParams({ showProjectModal: true, id });
  return {
    visible: showProjectModal == "true",
    projectDetailData,
    isLoading,
    open,
    close,
    queryProjectDetailFromID,
  };
};
